package com.jackrain.clouddata.sys.Listenter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.util.TypeUtils;
import com.jackrain.clouddata.oms.util.KeyValueUtils;
import com.jackrain.nea.core.db.Tools;
import com.jackrain.nea.exception.NDSException;
import com.jackrain.nea.web.query.QueryEngine;
import com.jackrain.util.WebUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * Created by nathan on 2017/8/14.
 */
@Component("com.jackrain.clouddata.sys.Listenter.ProClassMessageProcess")
@Slf4j
public class ProClassMessageProcess implements MessageProcess{

    @Override
    public void process(Object paramObject, String tag) throws Exception{
        JSONArray paramArray = JSONArray.parseArray(JSON.toJSONString(paramObject,new SerializerFeature[]{SerializerFeature.WriteMapNullValue}));
        try {
            if (paramArray != null && paramArray.size() > 0) {
                insertProClass(paramArray, tag);
            }
        }catch (Exception e){
            throw e;
        }
    }

    private void insertProClass(JSONArray jsonArray,String tag) throws Exception {
        //根据tag获取公司ID
        String clientIdSql = "SELECT AD_CLIENT_ID FROM OMS_TAG WHERE ISACTIVE='Y' AND TAGNAME = ?";
        JSONObject clientJson = QueryEngine.getInstance().doQueryObject(clientIdSql,new Object[]{tag});
        if (clientJson == null){
            throw new NDSException("公司ID未找到!");
        }
        Long clientId = clientJson.getLong("AD_CLIENT_ID");



        JSONArray proclassArray = new JSONArray();
        int incount = 0;
        for (int i=0;i<jsonArray.size();i++){
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            String code = jsonObject.getString("CLASSCODE");
            String countSql = "SELECT COUNT(*) FROM C_PROCLASS WHERE AD_CLIENT_ID = ? AND CLASSCODE = ?";
            int count = QueryEngine.getInstance().doQueryInt(countSql,new Object[]{clientId,code});
            JSONObject proclassJson = JSON.parseObject(JSON.toJSONString(jsonObject,new SerializerFeature[]{SerializerFeature.WriteMapNullValue}), Feature.OrderedField);
            for (int o=0;o<proclassJson.keySet().size();o++){
                String key = (String) proclassJson.keySet().toArray()[o];
                if (key.contains("DATE")){
                    proclassJson.put(key,TypeUtils.castToDate(jsonObject.getString(key)));
                }
            }

            if (count==0){
                proclassJson.put("AD_CLIENT_ID",clientId);
                proclassJson.put("ID", Tools.getSequence("C_PROCLASS"));
                proclassArray.set(incount,proclassJson);
                incount = incount + 1;
            }else if (count>0){
                proclassJson.remove("CLASSCODE");
                String updateSql = "UPDATE C_PROCLASS SET "+KeyValueUtils.keyUpdateAppend(proclassJson.keySet())+" WHERE AD_CLIENT_ID=? AND CLASSCODE=?";
                proclassJson.put("AD_CLIENT_ID",clientId);
                proclassJson.put("CLASSCODE",code);
                for (int j=0;j<proclassJson.keySet().size();j++){
                    String key = (String) proclassJson.keySet().toArray()[j];
                    String value = proclassJson.getString(key);
                    if(value == null){
                            proclassJson.remove(key);
                            updateSql = updateSql.replace(key+"=?,","");
                    }
                }

                QueryEngine.getInstance().executeUpdate(updateSql,proclassJson.values().toArray());
            }
            WebUtils.CallInterface(clientId,"OMS_C_PROCLASS",tag,jsonObject);
        }

        if (proclassArray != null && proclassArray.size()>0){
            StringBuffer insertSql = new StringBuffer();
            insertSql.append("INSERT INTO C_PROCLASS("+KeyValueUtils.keyAppend(proclassArray.getJSONObject(0).keySet())+") VALUES(").append(KeyValueUtils.valueAppend(proclassArray.getJSONObject(0).size())).append(")");
            QueryEngine.getInstance().executeBatchUpdate(insertSql.toString(),proclassArray);
        }

    }


}
